class UserQuery extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            users: [''],
            userView : {},
            menuList : []
        };
        this.roles = [''];
        this.page = 1;
    }


    componentDidMount() {
        postJson("/role/getRoleList.x", null,  (data) => {
            this.roles = data.data;
            let nodes = this.refs.treeModal.getNodes(data.data, null, 'roleParent', 'roleName', 'roleDisplay');
            this.setState({nodes: nodes});
            this.updateUserList(1,10);
        });
    }

    /* 判断某个角色是否属于某个角色的子角色 */
    userHasRole(userRoleName, roleName) {
        if(this.roles[0] == '')
            return false;

        if (userRoleName == roleName)
            return true;

        for (let i = 0; i < this.roles.length; i++) {
            if (this.roles[i].roleName == userRoleName) {
                let parents = this.roles[i].roleParents?this.roles[i].roleParents.split(","):"";
                for (let j = 0; j < parents.length; j++) {
                    if (parents[j] == roleName)
                        return true;
                }
            }
        }
        return false;

    }

    modify(userCode) {
        window.location.href = '/pages/sys_mng/user/forSave.html?modify=true&userCode='+userCode;
    }

    delete(userCode) {
        layui.layer.confirm('确实要删除该用户信息？', (index) => {
            let params = {};
            params.userCode = userCode;
            postJson("/user/remove.x",$.param(params), () => {
                layui.layer.msg("删除成功");
            });
            layui.layer.close(index);
            this.refs.table.refresh();
        });
    }

    updateUserList(page,pageSize) {
        let params = {
            page : page,
            pageSize : pageSize,
            logName : this.refs.logName.value,
            commCode : this.refs.commCode.value,
            roleName : this.refs.parentInput.value
        };
        postJson("/user/query.x", params, (data) =>{
            this.pageCount = data.data.size;
            this.setState({
                users: data.data.list
            });
        })
    }

    assignComm(userCode,commCount) {
        this.refs.modelAssignComm.show({typeData : '/pages/sys_mng/user/assignComm.html?userCode=' + userCode +'&commCount='+commCount});
    }

    resetPwd(userCode) {
        parent.layer.confirm('确实要重置密码？', function (index) {
            parent.layer.close(index);
            postJson("/LoginCtrl/resetPassword.x", {userCode : userCode},  (data) =>{
                if (data.ret_code == 1) {
                    layui.layer.alert("重置密码成功！初始密码123456");
                } else {
                    layui.layer.alert("重置密码失败！");
                }
            });

        });
    }

    stateCheck(userCode) {

        postJson("/user/getUserState.x", {userCode: userCode}, (data) => {
            let state = "";

            let msg = "";
            if (data.data == "locked") {
                msg = "当前账号被锁定,是否解锁?";
                state = "unlock";
            } else if (data.data == "open") {
                msg = "当前账号正常使用中,是否锁定此账号?";
                state = "lock";
            }

            let param = {
                userCode: userCode,
                state: state
            };
            layui.layer.alert(msg, (index) => {
                postJson("/user/setUserState.x", param, (data) => {
                    layui.layer.msg("操作成功!");
                    layui.layer.close(index);
                });
            });
        });

    }

    view(userCode){
        console.log("hehe")
        postJson("/user/view.x",{userCode:userCode},(data)=>{
            this.setState({userView:data.data},()=>{
                this.refs.modalUserDetail.show();
            })
        })
    }

    search(){
        this.refs.table.refresh();
    }

    batchDel(){
        if(this.refs.table.checkboxValue.length == 0){
            layui.layer.msg("请选中一条数据");
            return;
        }
        layui.layer.confirm("确认要删除选中的"+this.refs.table.checkboxValue.length+"条数据么?",()=>{
            postRJson("/user/removeBatchs.x",JSON.stringify(this.refs.table.checkboxValue),()=>{
                layui.layer.msg("删除成功!");
                this.refs.table.refresh();
            })
        });
    }

    getUserCommsSelect(comms){
        if(!comms)
            return (<option value="">未绑定小区</option>)
        else{
            let commList = comms.split(",");
            console.log(commList);
            let ret = [];
            for(let i=0; i < commList.length; i++){
                ret.push(<option>{commList[i]}</option>)
            }
            return ret;
        }
    }

    assignModal(userCode) {
        if (this.state.allMenuList) {
            postJson("/customer/getPermsOfCustomId.x", {id: userCode}, (roleMenus) => {
                let menuListOrdered = [];
                reorderParentsPermission(this.state.allMenuList, null, menuListOrdered, "menuPar", "menuCode");
                menuListOrdered = menuListOrdered.reverse();
                this.pageData = menuListOrdered;
                this.refs.tableModal.checkboxValue = roleMenus.data;
                this.tableRef = this.refs.tableModal;
                this.refs.tableModal.removeTreeTable();
                this.setState({menuList: menuListOrdered}, () => {
                    this.refs.assignModal.show({value:userCode});
                });
            })
        } else {
            postJson("/menu/query.x", null, (data) => {
                this.state.allMenuList = data.data;
                postJson("/customer/getPermsOfCustomId.x", {id: userCode}, (roleMenus) => {
                    let menuListOrdered = [];
                    reorderParentsPermission(data.data, null, menuListOrdered, "menuPar", "menuCode");
                    menuListOrdered = menuListOrdered.reverse();
                    this.pageData = menuListOrdered;
                    this.refs.tableModal.checkboxValue = roleMenus.data;
                    this.tableRef = this.refs.tableModal;
                    this.refs.tableModal.removeTreeTable();
                    this.setState({menuList: menuListOrdered}, () => {
                        this.refs.assignModal.show({value:userCode});
                    });
                })
            });
        }
    }

    assignMenu(){
        let userCode = this.refs.assignModal.value;
        layui.layer.confirm("确定分配么?",(index)=>{
            postJson("/menu/saveUserPerms.x",{userCode:userCode,perms:JSON.stringify(this.refs.tableModal.checkboxValue)},()=>{
                layui.layer.msg("分配成功");
                layui.layer.close(index);
                this.cancel();
            })
        })
    }

    cancel(){
        this.refs.assignModal.close();
    }

    render() {
        let showRoleList = hasRoles("admin")?{}:{display:"none"};
        return (
            <Frame header="后台账户管理">
                <Form type="pane">
                    <Item>
                        <Label>用户名称</Label>
                        <Input ref="logName"/>
                        <Label>小区编号</Label>
                        <Input name="commCode" ref="commCode"/>
                        <Label style={showRoleList}>角色类型</Label>
                        <Input ref="parentInput" onClick={()=>{this.refs.treeModal.show({typeData:this.refs.parentInput.refs.input})}}/>

                        <Button btnType="normal" onClick={() => this.search()}>查询</Button>
                    </Item>

                    <Table ref="table" count={this.pageCount} pageOnClick={(page,pageSize)=>this.updateUserList(page,pageSize)}
                           pageData={this.state.users} checkboxRenderCallback={()=>{this.setState({})}}
                           checkboxKeyname="userCode" size="xs"
                           toolbar = {[<Button btnType="danger" size="sm" onClick={()=>this.batchDel()}>批量删除</Button>]}
                    >
                        <thead>
                        <tr>
                            <th width={70}><TCheckbox  checkall="true" tableRef={this.refs.table} />&nbsp;&nbsp;全选</th>
                            <th>登录名</th>
                            <th>用户名称</th>
                            <th>所属角色</th>
                            <th>创建者</th>
                            <th>最近登录</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {

                            this.state.users.map((user) =>{
                                let userNotAdminStyle = user.logName == "admin" ? {display: "none"} : {};
                                let adminSeclevelShowStyle = hasRoles("admin | secLevel ") ? {} : {display: "none"};
                                let assignCommStyle = this.userHasRole(user.roleName, "secLevel")?{}:{display: "none"};
                                return (
                                    <tr>
                                        <td><TCheckbox data={user} tableRef={this.refs.table}/></td>
                                        <td>{user.logName}</td>
                                        <td>{user.userName}</td>
                                        <td>{user.roleName}</td>
                                        <td>{user.creater}</td>
                                        <td>{user.lastLogTime}</td>
                                        <td>
                                            <Button size="xs" onClick={() => this.view(user.userCode)}>查看</Button>
                                            <Button btnType="normal" size="xs" onClick={() => this.modify(user.userCode)} style={userNotAdminStyle}>修改</Button>
                                            <Button btnType="danger" size="xs" onClick={() => this.delete(user.userCode)} style={userNotAdminStyle}>删除</Button>
                                            <Button btnType="danger" size="xs" onClick={() => this.resetPwd(user.userCode)} style={adminSeclevelShowStyle}>重置密码</Button>
                                            <Button size="xs" onClick={() => this.stateCheck(user.userCode)} style={adminSeclevelShowStyle}>状态</Button>
                                            <Button btnType="primary" size="xs" onClick={() => this.assignModal(user.userCode)}>权限</Button>
                                            <Button btnType="normal" size="xs" onClick={() => this.assignComm(user.userCode,user.commCount)} style={assignCommStyle}>分配小区</Button>
                                        </td>
                                    </tr>
                                )
                            })

                        }
                        </tbody>
                    </Table>
                    <TreeModal ref="treeModal" nodes={this.state.nodes} onSelected={(string,data)=>{
                        this.refs.parentInput.value = data.roleName;
                    }}/>
                    <Modal modalType="iframe" ref="modelAssignComm" disableOverFlow="true" area={['450px','600px']}/>
                </Form>
                <Modal ref="modalUserDetail" title="用户详情">
                    <Table>
                        <tr>
                            <td>用户名</td>
                            <td>{this.state.userView.userName}</td>
                        </tr>
                        <tr>
                            <td>角色名</td>
                            <td>{this.state.userView.roleName}</td>
                        </tr>
                        <tr>
                            <td>最大小区数目</td>
                            <td>{this.state.userView.commCount}</td>
                        </tr>
                        <tr>
                            <td>管辖小区</td>
                            <td>
                                <Form size="sm">
                                    <Select>
                                        {this.getUserCommsSelect(this.state.userView.commCode)}
                                    </Select>
                                </Form>
                            </td>
                        </tr>
                        <tr>
                            <td>最近登录</td>
                            <td>{this.state.userView.lastLogTime}</td>
                        </tr>
                    </Table>
                </Modal>
                <Modal title="分配权限" ref="assignModal" disableOverFlow="true">
                    <Form>
                        <Table expandable="true" ref="tableModal" pageData={this.pageData} checkboxKeyname="menuCode"
                               size="sm"
                               toolbar={
                                   [
                                       <Button size="sm" onClick={() => this.assignMenu()}>确认分配</Button>,
                                       <Button size="sm" btnType="normal" onClick={() => this.cancel()}>取消</Button>
                                   ]
                               }>
                            <thead>
                            <tr>
                                <th width={70}>
                                    <i className="fa fa-chevron-up" onClick={()=>{this.refs.tableModal.collapseAll()}}/>&nbsp;&nbsp;&nbsp;&nbsp;
                                    <i className="fa fa-chevron-down" onClick={()=>{this.refs.tableModal.expandAll()}}/>
                                </th>
                                <th>菜单名称</th>
                                <th>菜单级别</th>
                                <th>权限字串</th>
                            </tr>
                            </thead>
                            <tbody>
                            {
                                this.state.menuList.length > 0 ? this.state.menuList.map((menu) => {
                                    return (
                                        <tr data-tt-id={menu.menuCode} data-tt-parent-id={menu.menuPar}>
                                            <td>&nbsp;{menu.type === 1 ? <TCheckbox keyname="menuCode" data={menu}
                                                                                    tableRef={this.tableRef}/> : ''}</td>
                                            <td>{menu.type !== 0 ? <i className="fa fa-key"
                                                                      style={{marginRight: 5}}/> : ''}{menu.menuName}</td>
                                            <td>{menu.menuLev}</td>
                                            <td>{menu.permission}</td>
                                        </tr>
                                    )
                                }) : ''
                            }
                            </tbody>
                        </Table>
                    </Form>
                </Modal>
            </Frame>
        )
    }

}

ReactDOM.render(<UserQuery/>, document.getElementById("query"));